<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>科泰聊天室</title>
  <link href="css/chat.css" rel="stylesheet">
</head>
<body>
  <div id="app">
    <h1 class="title center">科泰聊天室</h1>
    <div class="chat-window center">
      <div class="chat-messages">
        <!-- 显示消息的容器 -->
        <div class="message received-message" v-for="message in messages" :class="message.type">
          <div class="message-{{message.type === 'received-message'? 'received' : 'sent'}}">
            <img :src="message.avatar" class="avatar">
            <span class="message-content">{{message.content}}</span>
          </div>
        </div>
      </div>
      <!-- 输入框和按钮作为子组件 -->
      <chat-input @send-message="addMessage"></chat-input>
    </div>
  </div>

  <script src="js/vue.js"></script>
  <script src="https://unpkg.com/axios@1.6.7/dist/axios.min.js"></script>
  <script>
    Vue.component('chat-input', {
      template: `<div class="chat-input"><input type="text" v-model="inputMessage" placeholder="请输入消息..."> <button @click="sendMessage">发送</button></div>`,
      data() {
        return {
          inputMessage: ''
        };
      },
      methods: {
        sendMessage() {
          this.$emit('send-message', this.inputMessage);
          this.inputMessage = '';
        }
      }
    });

    new Vue({
      el: '#app',
      data: {
        messages: []
      },
      created() {
        // 在组件创建时发送请求获取聊天记录数据
        this.loadChatHistory();
      },
      methods: {
        addMessage(message) {
          this.messages.push({ type:'sent-message', avatar: 'images/avt-02.png', content: message });
        },
        loadChatHistory() {
          axios.get('data/chat-history.json')
          .then(response => {
              // 将获取到的聊天记录数据赋值给messages数组
              this.messages = response.data;
            })
          .catch(error => {
              console.log('请求聊天记录出错：', error);
            });
        }
      }
    });
  </script>
</body>
</html>